package cn.tannn.surenessdemo.user.dao;

import cn.tannn.surenessdemo.user.entity.AuthRole;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author tan
 * @date 2022-07-18 11:00:57
 */
public interface AuthRoleDao extends JpaRepository<AuthRole, Long> {

    /**
     * 查询当前用户所拥有的角色
     * @param username username
     * @return role list
     */
    @Query("select ar.name from AuthRole ar, AuthUser au, AuthUserRoleBind bind " +
            "where ar.code = bind.roleCode and au.code = bind.userCode and au.username = :username")
    List<String> findAccountOwnRoles(@Param("username") String username);

    /**
     * 判断角色是否存在
     * @param code 角色code
     * @return boolean
     */
    boolean existsByCode(String code);


    /**
     * 查询
     * @param code code
     * @return AuthRole
     */
    AuthRole findByCode(String code);

    /**
     * 删除角色
     * @param roleCode 角色code
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    void deleteByCode(String roleCode);




    /**
     * 更新状态
     * @param codes codes
     * @param status status  角色状态： 1:启用、0：禁用
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query("update AuthRole ar set ar.status = :status where  ar.code in (:codes) ")
    void changeStatus(@Param("codes") List<String> codes ,@Param("status") Integer status);

}
